#!/usr/bin/ruby

require "sqlite3"

require 'pp'

def time2text(t)
    return t.strftime("%A, %B %d, %H:%M")
end

def join_recs(start_t_list)
    #f = File.new("/home/yovadia/scanner-recorder/test.ogg", 'r')
    #$stdout.write(f.read())
    #return
    start_t_list.sort!
    db = SQLite3::Database.new(DB_FILE)
    entries = start_t_list.map do |start_t|
        db.execute("SELECT * FROM Recordings WHERE start_t == #{start_t}")[0]
    end.uniq
    
    temp_dir = `mktemp -d`[0..-2]
    outfile = "#{temp_dir}/join.ogg"
    n = entries.length
    
    fnames = entries.map {|x| x[FNAME_DB_IDX]}
    times  = entries.map {|x| Time.at(x[START_T_DB_IDX].to_i) }
    time_audio_l = times.map \
        {|t| "#{temp_dir}/#{t.to_i}.#{OUT_AUD_FORMAT}"}
    
    n.times {|i| `echo "#{time2text(times[i])}" \
        | text2wave | sox - -c 1 -r #{RATE} #{time_audio_l[i]}`}
    
    files = (0..n-1).map {|i| "#{time_audio_l[i]} #{fnames[i]}"}.join(' ')
    `sox #{files} #{outfile}`

    f = File.new(outfile, 'r')
    $stdout.write(f.read())
    f.close()

    `rm #{outfile}`
    time_audio_l.each {|f| `rm #{f}`}
    `rmdir  #{temp_dir}`
end

